//创建和购物车相关的reduer处理函数
let initState = [
  {
    id: 12,
    title: '尼康相机',
    img: 'https://wap.meishangyun.com/uploads/home/store/goods/2020030516272786144_240.jpg',
    price: 11,
    num: 1, // 购买的数量
    selectStatus: true, // 选中状态
  },
  {
    id: 13,
    title: '尼康相机',
    img: 'https://wap.meishangyun.com/uploads/home/store/goods/2020030516272786144_240.jpg',
    price: 10,
    num: 1, // 购买的数量
    selectStatus: true, // 选中状态
  },
]
export const cartReducer = (state = initState, action) => {
  switch (action.type) {
    // 添加至购物车
    case 'ADDTOCART':
      let id = action.payload.id
      let indexNum = state.findIndex(v => v.id === id)
      console.log(indexNum, 'indexnum')
      // 查找当前商品是否有存在-如果存在则添加1
      if (indexNum !== -1) {
        state[indexNum].num += 1
        return [...state] //如果有修改必须return一个全选的
      } else {
        // 如果没有则,添加一个新商品数组
        console.log('当前购物车还没有商品-添加一个新商品数组')
        return [...state,action.payload]
      }
    // -减
    case 'SUbBTRACT':
      let SUbBTRACT_Id = action.payload.id
      let SUbBTRACT_index = state.findIndex(v => v.id === SUbBTRACT_Id)
      console.log(SUbBTRACT_index, 'SUbBTRACT_index')
      if (state[SUbBTRACT_index].num > 1) {
        state[SUbBTRACT_index].num--
        return [...state]
      }
      return state
    // +加
    case 'ADD':
      let ADD_Id = action.payload.id
      let ADD_index = state.findIndex(v => v.id === ADD_Id)
      console.log(ADD_index, 'ADD_index')
        state[ADD_index].num++
        return [...state]
    //修改勾选状态
    case 'SELECTSTATES':
      let SELECTSTATES_Id = action.payload.id
      let SELECTSTATES_index = state.findIndex(v => v.id === SELECTSTATES_Id)
      console.log(SELECTSTATES_index, 'SELECTSTATES_index')
        state[SELECTSTATES_index].selectStatus=!state[SELECTSTATES_index].selectStatus
        return [...state]
    //全选修改勾选状态
    case 'SELECTSAllTATES':
      state.map(v => {
        v.selectStatus=action.playload.ischeckState
      })
        return [...state]
    //修改勾选状态
    case 'DELETEITEM':
      let DELETEITEM_Id = action.playload.id
      // 这里filter出来一个全新的state,所以不需要[...state]
      return state.filter(v=>v.id!==DELETEITEM_Id)
    default:
      return state
  }
}